package com.voicecall.voicecall.controller;

import com.voicecall.voicecall.utils.HttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wawayang on 2019/1/10.
 */
@Controller
@PropertySource({"classpath:resource.properties"})
public class TosController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${itf.ip}")
    private String url;
    @Value("${call.ip}")
    private String callUrl;

    @RequestMapping("/")
    @ResponseBody
    String home() {
        System.out.print("什么情况");
        System.out.print("什么情况1");
        System.out.print("\n");
        System.out.print("什么情况3");
        System.out.print("什么情况4");
        logger.info("123");
        logger.debug("444");
        logger.error("zero");
        return "helloworld123";
    }

    @PostMapping(value = "/api/callback")
    @ResponseBody
    /**
     *    accept = 1是接听2是没接听
     *    phone 为调用uc呼叫中心呼叫接口的手机号码
     *    checkid 是调用接口时候返回的id
     */
    public Object callBack(String accept, String phone, String checkid) {

        Map<String, Object> params = new HashMap<>();

        params.clear();
        params.put("accept", accept);
        params.put("phone", phone);
        params.put("checkid", checkid);

        String result = null;
        try {

            logger.info("accept: " + accept + " phone: " + phone + " checkid: " + checkid);
            System.out.println("accept: " + accept + " phone: " + phone + " checkid: " + checkid);

            //resp.getWriter().write(respString);
            StringBuffer msg = new StringBuffer();
            result = HttpClient.postITFByNormal(url, "GATE_MS", "GATE_VOC_CALLBACK", "wsdMonitorService", accept, phone, checkid, null, msg);
//            result = HttpClient.postITFByNormal(url, "STS_MS", "STS_MS_MAIN_PICK_UP_CNTR", "wsdMonitorService", accept, null, null, null, msg);

            logger.info("result: " + result);
            System.out.println("resultx-out: " + result);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            System.out.println("callBack: " + e.getMessage());
        }

//        return result;
        return result;
    }


    @PostMapping(value = "/api/call")
    @ResponseBody
    public String voiceCall(String params) {

        String body = "";

        try {


            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
//        String radioUrl = "https://cloud2.ucserver.cc/uctts/Public/";
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(callUrl);

            //装填参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        if(map!=null){
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//            }
//        }
            //设置参数到请求对象中
//        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
//        String json = charReader(req);
            logger.info("VoiceCall: " + " Json:" + params + "   \n");//记录EIR报文日志

            nvps.add(new BasicNameValuePair("service", "TTS.boardNotice"));
            nvps.add(new BasicNameValuePair("params", params));


            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
//
//        StringEntity s = new StringEntity(param, "UTF-8");
//        httpPost.setEntity(s);


            System.out.println("VoiceCall请求地址：" + callUrl);
            logger.info("VoiceCall请求地址：" + callUrl);
//        System.out.println("请求参数："+s);

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/json");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, HTTP.UTF_8);
                System.out.println("VoiceCall: " + " Result:" + body + "   \n");//记录body报文结果日志
                logger.info("VoiceCall: " + " Result:" + body + "   \n");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            System.out.println("voiceCall: " + e.getMessage());

        } finally {
        }
        return body;

    }
}
